package com.auto.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auto.entity.Art;
import com.auto.entity.Site;
import com.auto.entity.Task;
import com.auto.rep.SiteRep;
import com.auto.rep.TaskRep;
import com.auto.util.BeanUtil;
import com.google.common.collect.Lists;

@Controller
public class TaskController {

	@Autowired
	private TaskRep taskRep;
	@Autowired
	private SiteRep siteRep;

	@RequestMapping(value = "task", method = RequestMethod.GET)
	@ResponseBody
	public List<Task> getTasks() {
		return Lists.newArrayList(taskRep.findAll());
	}

	@RequestMapping(value = "task/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Task getTask(@PathVariable("id") Long id) {
		return taskRep.findOne(id);
	}

	@RequestMapping(value = "task/{id}", method = RequestMethod.POST)
	@ResponseBody
	public void updateTask(@PathVariable("id") Long id, Task task) {
		task.setId(id);
		taskRep.save(task);
	}

	@RequestMapping(value = "task/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public void deleteTask(@PathVariable("id") Long id) {
		taskRep.delete(id);
	}

	@RequestMapping(value = "task", method = RequestMethod.POST)
	@ResponseBody
	public Task addTask(Task task,
			@RequestParam(value = "artId", required = false) Long[] artIds,
			@RequestParam("siteId") Long siteId) {
		Site site = siteRep.findOne(siteId);
		task.setSite(site);
		if (artIds != null) {
			List<Art> arts = BeanUtil.getBeanByIdsList(artIds, Art.class);
			task.setArts(arts);
		}
		return taskRep.save(task);
	}

	@RequestMapping(value = "task/{id}/stop", method = RequestMethod.POST)
	@ResponseBody
	public void stop(@PathVariable("id") Long id) {
		Task task = taskRep.findOne(id);
		task.setFlag(0);
		taskRep.save(task);
	}

	@RequestMapping(value = "task/{id}/start", method = RequestMethod.POST)
	@ResponseBody
	public void start(@PathVariable("id") Long id) {
		Task task = taskRep.findOne(id);
		task.setFlag(1);
		taskRep.save(task);
	}
}
